package com.njtcedu.microblog.website.home.repository;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import org.apache.commons.codec.digest.DigestUtils;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;
import org.springframework.web.multipart.MultipartFile;
import com.njtcedu.microblog.common.entity.User;
import com.njtcedu.microblog.common.entity.UserInfo;
import com.njtcedu.microblog.common.exception.BusinessException;
import com.njtcedu.microblog.common.repository.AbstractRepository;
import com.njtcedu.microblog.common.repository.CompressImage;
import com.njtcedu.microblog.common.repository.RowMapper;
import com.njtcedu.microblog.common.util.StringUtils;
import com.njtcedu.microblog.intranet.systemconfig.web.response.AdImageResponse;
import com.njtcedu.microblog.website.home.web.request.UserRegisterRequest;
import com.njtcedu.microblog.website.home.web.response.CurrentUser;

@Repository
public class HomeRepository extends AbstractRepository {

	public void register(UserRegisterRequest request) {
		if (!StringUtils.hasText(request.getEmail())) {
			throw new BusinessException("用户Email不能为空");
		}
		
		User user = hibernateAccess.findUniqueResult(DetachedCriteria.forClass(User.class).add(Restrictions.eq("account", request.getEmail())));
		if (user !=null) {
			throw new BusinessException("用户Email[" + request.getEmail() + "]已经存在");
		}
		
		user = new User();
		user.setAccount(request.getEmail());
		user.setPassword(DigestUtils.md5Hex(request.getPassword()));
		user.setUserType("ORDINARY");
		user.setStatus("Y");
		hibernateAccess.persist(user);
		hibernateAccess.currentSession().flush();
		
		UserInfo userInfo = new UserInfo();
		userInfo.setNickName(request.getNickName());
		userInfo.setUser(user);
		userInfo.setSignupDate(getSysDate());
		userInfo.setUserImage("/upload/image/noavatar.gif");
		hibernateAccess.persist(userInfo);
		hibernateAccess.currentSession().flush();
		
		user.setUserInfo(userInfo);
		hibernateAccess.update(user);
	}

	public CurrentUser login(String account, String password) {
		if (!StringUtils.hasText(account)) {
			throw new BusinessException("用户账户不能为空");
		}
		
		User user = hibernateAccess.findUniqueResult(DetachedCriteria.forClass(User.class).add(Restrictions.eq("account", account)));
		if (user == null) {
			throw new BusinessException("用户[" + account + "]不存在");
		}
		
		if (!StringUtils.hasText(password)) {
			throw new BusinessException("密码不能为空");
		}
		
		if (!DigestUtils.md5Hex(password).equals(user.getPassword())) {
			throw new BusinessException("密码错误");
		}
		
		String contentSql = "select count(*) as total from content where user_id = ?";
		
		Integer contentNums = jdbcAccess.findUniqueResult(contentSql, new RowMapper<Integer>() {

			@Override
			public Integer mapRow(ResultSet resultSet, int rowNum) throws SQLException {
				return resultSet.getInt("total");
			}
		}, user.getId());
		
		if (contentNums == null )
			contentNums = new Integer(0);
		UserInfo userInfo = hibernateAccess.findUniqueResult(DetachedCriteria.forClass(UserInfo.class).add(Restrictions.eq("user", user)));
		CurrentUser currentUser = new CurrentUser();
		currentUser.setContentNums(contentNums);
		currentUser.setUserId(user.getId());
		currentUser.setNickName(userInfo.getNickName());
		currentUser.setAccount(user.getAccount());
		currentUser.setUserImage(userInfo.getUserImage());
		return currentUser;
	}
	
	public AdImageResponse uploadAdImage(MultipartFile imageFile, String evePath, CurrentUser currentUser) throws IOException {
		
		String fileName ="/upload/image/" + UUID.randomUUID().toString() + imageFile.getOriginalFilename().substring(imageFile.getOriginalFilename().lastIndexOf("."));
		String targetPath = evePath + fileName;
		InputStream uploadStream = null;
		OutputStream targetStream = null;
		AdImageResponse response = new AdImageResponse();
		response.setImageUrl(fileName);		
		try {
			uploadStream = imageFile.getInputStream();
			targetStream = new FileOutputStream(targetPath);
			byte[] cache = new byte[50];
			int count = -1;
			while ((count = uploadStream.read(cache)) != -1) {
				targetStream.write(cache, 0, count);
				targetStream.flush();
			}
		} catch (Exception e) {
			throw new BusinessException("文件写入失败.");
		} finally {
			if (null != targetStream)
				targetStream.close();
			if (null != uploadStream)
				uploadStream.close();
		}
		
		CompressImage compressImage = CompressImage.getInstance();
		compressImage.compress(targetPath, targetPath, 120, 120);
		
		User user = hibernateAccess.get(User.class, currentUser.getUserId());
		UserInfo info = user.getUserInfo();
		info.setUserImage(fileName);
		hibernateAccess.update(info);
		return response;
	}
	
	public List<CurrentUser> getTop10User() {
		List<CurrentUser> currentUsers = new ArrayList<CurrentUser>();
		
		List<User> users = hibernateAccess.find(DetachedCriteria.forClass(User.class));
		for (User user : users) {
			UserInfo userInfo = user.getUserInfo();
			CurrentUser currentUser = new CurrentUser();
			currentUser.setUserId(user.getId());
			currentUser.setNickName(userInfo.getNickName());
			currentUser.setAccount(user.getAccount());
			currentUser.setUserImage(userInfo.getUserImage());
			currentUsers.add(currentUser);
		}
		
		return currentUsers;
		
	}
}
